const getBrowser = require('../browser/init');
const DBOP = require('../dao/book');
var num = 1;

main();

async function main() {
  const browser = await getBrowser();
  const page = await browser.newPage();
  const readUrl = await DBOP.getAllBookContent();
  for (let i = 0; i < readUrl.length; i++) {
    num = 1;
    const url = readUrl[i].readUrl;
    await page.goto(url);
    const bookName = readUrl[i].bookname;
    try {
      // const author = await getAuthor(page);
      // const value = [bookName, author];
      // await DBOP.insertAuthorBook(value); // 插入作者-书籍
      const isEnd = await getContent(page, bookName).catch(() => true); // 递归插入章节内容
      if (isEnd) continue;
    } catch (error) {
      console.log(error);
      continue;
    }
  }
}

// 获取书籍当页内容
async function getContent(page, bookName) {
  if (num > 10) return true; // 只取前十章
  const content = await getContentByUrl(page);
  const chapter = await getChapter(page);
  await DBOP.insertBookContent([bookName, chapter, content]);
  console.log(`《${bookName}》---${chapter}---插入成功！`);
  const flag = await checkEnd(page);
  if (!flag) {
    const nextPage = await page.$eval('.nextchapter', el => el.getAttribute('href'));
    await page.goto(nextPage);
    num++;
    await getContent(page, bookName);
  } else {
    return true;
  }
}
// 获取作者名称
async function getAuthor(page) {
  return await page.$eval('.bookinfo > a:nth-child(1)', el => el.innerText);
}
//  获取书籍内容
async function getContentByUrl(page) {
  return await page.$eval('.content', el => el.innerText);
}
//  获取书籍章节名
async function getChapter(page) {
  return await page.$eval('.title_txtbox', el => el.innerText);
}

// 判断是否最后一页
async function checkEnd(page) {
  const checkVip = await page.$eval('#reader-order-box', () => true).catch(() => false);
  if (checkVip) return true; // 是vip 退出

  const isEnd = await page.$eval('#endPageDialogTarget', () => true).catch(() => false);
  return isEnd;
}
